<template>
  <div class="login">
    <div class="login-item">
      <div class="login-item-title">手机号/邮箱</div>
      <div class="login-item-info">
        <input placeholder="请输入手机号或邮箱" autocomplete="off" type="text" v-model="teleml"/>
        <div v-show="hasTel" @click="clearStr('teleml')" class="login-item-info-icon"><i class="iconfont icon-cha"></i></div>
      </div>
    </div>
    <div class="login-item">
      <div class="login-item-title">密码</div>
      <div class="login-item-info">
        <input placeholder="请输入密码" autocomplete="off" :type="this.flag? 'password':'text'" v-model="ma"/>
        <div @click="show" class="login-item-info-icon"><i :class="flag ?'iconfont icon-close-eye':'iconfont icon-yanjing'"></i></div>
        <div v-show="hasMa"  @click="clearStr('ma')" class="login-item-info-icon"><i class="iconfont icon-cha"></i></div>
        <div class="login-item-info-btn login-item-info-btn2">忘记密码</div>
      </div>
    </div>
    <!---->
    <button class="to-login" @click="login">登录</button>
    <div class="login-by-password" @click="loginChange('ckma')">手机短信登录</div>
  </div>
</template>

<script>
import Vue from 'vue'
import { mapMutations } from 'vuex'
import * as types from '@/store/mutation.types'
import { Toast } from 'vant'
import { emlLogin } from '@/api'
Vue.use(Toast)
export default {
  data () {
    return {
      teleml: '',
      ma: '',
      hasTel: false,
      hasMa: false,
      flag: true
    }
  },
  props: {
    loginStyle: {
      type: String,
      default: 'pwd'
    }
  },
  methods: {
    ...mapMutations('users', [types.CHANGE_LOGIN_STATE]),
    loginChange (val) {
      this.$emit('my-event', val)
    },
    clearStr (val) {
      // console.log(val)
      if (val === 'teleml') {
        this.teleml = ''
      } else if (val === 'ma') {
        this.ma = ''
      }
    },
    login () {
      if (!this.teleml) {
        Toast('手机邮箱不能为空')
      } else if (!this.ma) {
        Toast('请输入密码')
      } else {
        // console.log(this.teleml, this.ma)
        emlLogin({ email: this.teleml, password: this.ma }).then(res => {
          console.log(res)
          if (res.data.code === '10888') {
            localStorage.setItem('loginState', 'ok')
            localStorage.setItem('userid', res.data.data.userid)
            localStorage.setItem('token', res.data.data.token)
            localStorage.setItem('nickname', res.data.data.nickname)
            this[types.CHANGE_LOGIN_STATE]({
              payload: true
            })
            Toast('登录成功')
            this.$router.push('/user')
          }
        })
      }
    },
    show () {
      this.flag = !this.flag
    }
  },
  watch: {
    teleml (newval, oldVal) {
      if (newval.length > 0) {
        this.hasTel = true
      }
    },
    ma (newval, oldVal) {
      if (newval.length > 0) {
        this.hasMa = true
      }
    }
  }
}
</script>

<style></style>
